package com.hongliang.nio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 使用 FileChannel 来读取文件内容
 *
 * @author Hongliang Zhu
 * @create 2022-11-03 23:12
 */
@Slf4j
public class ChannelDemo1 {
    public static void main(String[] args) {
        String path = ChannelDemo1.class.getClassLoader().getResource("hello/data.txt").getPath();
        try (RandomAccessFile file = new RandomAccessFile(path, "rw")) {

            FileChannel channel = file.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(10);
            do {
                // 向buffer写入数据
                int len = channel.read(buffer);
                log.debug("读取到的字节数： " + len);
                if (len == -1){
                    break;
                }

                // 切换buffer 读模式
                buffer.flip();

                while (buffer.hasRemaining()){
                    log.debug("{}", (char)buffer.get());
                }
                // 切换 buffer 写模式
                buffer.clear();



            }while (true);

        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }
}
